/**
* Description here...
* @author Default
* @version 0.1
*/

package engine.materials
{
	
	import engine.materials.Material;
	import engine.geom.Face;
	import engine.geom.Vector;
	import engine.utils.Raster;
	import engine.math.VectorUtils;
	import flash.display.Sprite;
	import flash.display.Graphics;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.geom.Rectangle;
	
	public class RasterColor extends Material
	{
		private var bmp:Bitmap;
		private var red:int = 255;
		private var green:int = 255;
		private var blue:int = 255;
		public var lightPos:Vector = new Vector(1,1,1);
		
		public function RasterColor ( screen:Sprite, lp:Vector )
		{
			super( null );
			bmp = new Bitmap ( new BitmapData ( screen.width,screen.height, true, 0x00 ) );
			screen.addChild( bmp );
			lightPos = lp;
		}
		
		public override function render ( face:Face, screen:Sprite ) : void
		{
			// get vertices x,y positions
			var v0:Object = face.vertices[0];
			var v1:Object = face.vertices[1];
			var v2:Object = face.vertices[2];

			var x0:Number = v0.x;
			var y0:Number = v0.y;
			var z0:Number = v0.z;
			var x1:Number = v1.x;
			var y1:Number = v1.y;
			var z1:Number = v1.z;
			var x2:Number = v2.x;
			var y2:Number = v2.y;	
			var z2:Number = v2.z;

			var MAXLIGHT:Number = 32;
			var nx:Number = ( ( y0 - y1 ) * ( z0 - z2 ) ) - ( ( z0 - z1 ) * ( y0 - y2 ) );
			var ny:Number = ( ( z0 - z1 ) * ( x0 - x2 ) ) - ( ( x0 - x1 ) * ( z0 - z2 ) );
			var nz:Number = ( ( x0 - x1 ) * ( y0 - y2 ) ) - ( ( y0 - y1 ) * ( x0 - x2 ) );
			var PlaneNormal:Vector = new Vector ( nx, ny, nz );
			
			if ( lightPos.x == 0 ) lightPos.x = 1;
			if ( lightPos.y == 0 ) lightPos.y = 1;
			if ( lightPos.z == 0 ) lightPos.z = 1;
			var lightNormal:Vector = new Vector ( -lightPos.x, lightPos.y, -lightPos.z );
			
			PlaneNormal = VectorUtils.Normalize( PlaneNormal );
			lightNormal = VectorUtils.Normalize( lightNormal );
			
			var dot:Number = VectorUtils.dot(PlaneNormal,lightNormal);	
			var light:Number = Math.cos (MAXLIGHT+dot);
			
			if(light<0)light=0;

			var cr:Number = (red * light);
			var cg:Number = (green * light);
			var cb:Number = (blue * light);
			
			var fColor:Number = 255 << 24 | cr << 16 | cg << 8 | cb;
			
			// Draw triangle
			x0 = v0.screen.x;
			y0 = v0.screen.y;
			x1 = v1.screen.x;
			y1 = v1.screen.y;
			x2 = v2.screen.x;
			y2 = v2.screen.y;

			Raster.filledTri( bmp.bitmapData, x0,y0,x1,y1,x2,y2, fColor );
		}
		
	}
	
}
